package com.voicechat.firstmet.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.luck.picture.lib.entity.LocalMedia;
import com.voicechat.firstmet.MainActivity;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.CropBean;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PersonDataBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.LoginService;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.ConstantSet;
import com.voicechat.firstmet.utils.DisplayUtil;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.TimerUtil;
import com.voicechat.firstmet.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.voicechat.firstmet.utils.PopUtils.hidePopupWindow;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: RealNameActivity
 * @Description: 实名认证页面
 * @Author: ljp
 * @CreateDate: 2018/10/12 13:45
 * @Version: 1.0
 */
public class RealNameActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_card_number)
    EditText etCardNumber;
    @BindView(R.id.et_phone_number)
    EditText etPhoneNumber;
    @BindView(R.id.et_valide_code)
    EditText etValideCode;
    @BindView(R.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R.id.rela_add_front)
    RelativeLayout relaAddFront;
    @BindView(R.id.circle_front)
    ImageView circleFront;
    @BindView(R.id.rela_add)
    RelativeLayout relaAdd;
    @BindView(R.id.circle_reverse)
    ImageView circleReverse;
    @BindView(R.id.tv_uploading)
    TextView tvUploading;
    @BindView(R.id.rela_front)
    RelativeLayout relaFront;
    @BindView(R.id.rela_reverse)
    RelativeLayout relaReverse;
    @BindView(R.id.linear_data)
    LinearLayout linearData;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    @BindView(R.id.et_name_real)
    EditText etNameReal;
    @BindView(R.id.et_card_number_real)
    EditText etCardNumberReal;
    @BindView(R.id.et_phone_number_real)
    EditText etPhoneNumberReal;
    @BindView(R.id.tv_back_home)
    TextView tvBackHome;
    @BindView(R.id.linear_real_name)
    LinearLayout linearRealName;
    private List<LocalMedia> selectList;
    private String TAG = "RealNameActivity";
    private Uri uritempFile;
    private File file;
    private Uri imageUri;
    private int flag;//判断点击的是哪个按钮
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private List<String> images;
    private TimerUtil mTimer;
    private String mobile;
    private String token;
    private String deviceInfo;
    private PersonDataBean.ObjectBean object;
    public static File bgFile = new File(Environment.getExternalStorageDirectory(), "photo_bg.jpg");
    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_real_name;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        ButterKnife.bind(this);
        object = getIntent().getParcelableExtra("object");
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        initView();
    }

    private void initView() {
        if (object == null) {
            scrollView.setVisibility(View.VISIBLE);
            mobile = SPUtils.getEditoString(SPUtils.SP_PHONE);
            mTimer = new TimerUtil(60, tvGetCode, this);
            images = new ArrayList<>();
            file = new File(ConstantSet.PICTUREREAL + ConstantSet.USERTEMPPIC);
            imageUri = Uri.fromFile(file);//The Uri t
            etPhoneNumber.setText(mobile);
            etPhoneNumber.setEnabled(false);
        } else {
            //判断state状态  认证状态 0审核中 1审核通过 2驳回
            if (object.getStatus() == 1) {
                linearRealName.setVisibility(View.VISIBLE);
                etPhoneNumberReal.setText(object.getMobile());
                etCardNumberReal.setText(object.getIdCard());
                etNameReal.setText(object.getName());
            } else if (object.getStatus() == 2) {

            }
        }
        etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String strs=etName.getText().toString();
                /*if (!strs.equals(str)) {
                    etName.setText(str);
                    etName.setSelection(str.length());
                }*/
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }
    @OnClick({R.id.linear_back, R.id.tv_get_code, R.id.tv_uploading, R.id.rela_front, R.id.rela_reverse})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                finish();
                break;
            case R.id.tv_get_code:
                setCode();
                break;
            case R.id.tv_uploading:

                setHttpSave();
                break;
            case R.id.rela_front:
                setPopuWindow(ConstantSet.TAKEPICTURE);//正面照
                flag = 0;
                break;
            case R.id.rela_reverse:
                setPopuWindow(ConstantSet.SELECTPICTURE);// 反面照
                flag = 1;
                break;
        }
    }

    /**
     * @return
     * @method
     * @description 弹出popuWindow
     * @date: 2018/11/21 21:41
     * @author: ljp
     */
    public void setPopuWindow(int code) {
        View view = View.inflate(this, R.layout.pop_repl_picture, null);
        PopUtils.initPopupWindow(activity, view, false);
        //实例化控件
        TextView tvPhotoAlbum = view.findViewById(R.id.tv_photo_album);
        TextView tvPhotograph = (TextView) view.findViewById(R.id.tv_photograph);
        TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        //取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidePopupWindow();
            }
        });
        tvPhotograph.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //拍照
                if (Build.VERSION.SDK_INT >= 23) {
                    int checkCallPhonePermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
                    if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA}, 222);
                        return;
                    } else {
                        openCamra(code);//调用具体方法
                    }
                } else {
                    openCamra(code);//调用具体方法
                }
            }
        });
        //相册
        tvPhotoAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //拍照
                if (Build.VERSION.SDK_INT >= 23) {
                    int checkCallPhonePermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
                    if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 223);
                        return;
                    } else {
                        openIcon(code);//调用具体方法
                    }
                } else {
                    openIcon(code);//调用具体方法
                }
            }
        });

    }

    /**
     * @return
     * @method
     * @description 打开相机
     * @date: 2018/8/31 11:45
     * @author: ljp
     */
    private void openCamra(int code) {
       /* Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, code);//or TAKE_SMALL_PICTURE*/
        //指定相机意图
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //如果TargetSdkVersion >= 24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //getUriForFile(Context context, String authority, File file)
            //authority需要和AndroidManifest中的authorities属性保持一致
            Uri photoUri = FileProvider.getUriForFile(activity, context.getPackageName() + ".android7.fileprovider", bgFile);
            Log.i("mengyuanuri", "SDK>=24相机拍摄存储的uri:" + photoUri.getScheme() + ":" + photoUri.getSchemeSpecificPart());
            //申请权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //设置相片保存的地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        } else {
            //设置相片保存的地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(bgFile));
        }
        activity.startActivityForResult(intent, code);
        hidePopupWindow();

    }

    /**
     * @return
     * @method
     * @description 获取验证码
     * @date: 2018/11/6 10:16
     * @author: ljp
     */
    private void setCode() {
        LoginService.loginGetVCode(mobile, LoginService.VALIDATE_CODE_TYPE.VALIDATE_CODE_REALNAME).subscribe(result -> {
            Log.i(TAG, "getVaCode: ----" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                mTimer.myStart(0);
                toast_MakeText(result.getMsg());
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "getVaCode: -----" + throwable.toString());

        });
    }

    /**
     * @return
     * @method
     * @description 保存实名认证信息
     * @date: 2018/11/6 10:09
     * @author: ljp
     */
    private void setHttpSave() {
        String cardNum = etCardNumber.getText().toString().trim();
        String name = etName.getText().toString().trim();
        String code = etValideCode.getText().toString().trim();
        if (!Utils.isCardNumber(cardNum)) {
            toast_MakeText("请输入正确的身份证号码");
        } else if (code.length() < 4) {
            toast_MakeText("请输入正确的验证码");
        } else if (name.length() < 2) {
            toast_MakeText("请输入正确的姓名");
        } else if (images.size() < 2) {
            toast_MakeText("身份证照片不全");
        } else {
            tvUploading.setEnabled(false);
            String s1 = Utils.spitString(images.get(0));
            String s = Utils.spitString(images.get(1));
            MeInfoService.realName(mySeleInfo.getId(), token, deviceInfo,
                    cardNum, mobile, code, s1, s, name).subscribe(result -> {
                if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    mySeleInfo.setIsAttestation(2);
                    SPUtils.setEditorKeyValue(SPUtils.SP_MYSELFINFO, ParcelableUtils.marshall(mySeleInfo));
                    Intent intent = new Intent(activity, MainActivity.class);
                    intent.putExtra("flag", 4);
                    startActivity(intent);
                } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                    tvUploading.setEnabled(true);
                    Utils.setToken(context);
                } else {
                    tvUploading.setEnabled(true);
                    toast_MakeText(result.getMsg());
                }
                Log.i(TAG, "setHttpSave: -----------" + result.toString());
            }, throwable -> {
                tvUploading.setEnabled(true);
                Log.i(TAG, "setHttpSave: -----" + throwable.toString());
            });


        }
    }

    /**
     * @return
     * @method
     * @description 选择相册
     * @date: 2018/8/31 14:54
     * @author: ljp
     */
    private void openIcon(int code) {
       /* Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        //intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, code);*/
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_GET_CONTENT);
        // 设置文件类型
        intent.setType("image/*");
        activity.startActivityForResult(intent, code);
        hidePopupWindow();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ConstantSet.TAKEPICTURE:
                    Log.i(TAG, "onActivityResult: -------data----"+data);
                    if(data == null){
                        startCrop(Uri.fromFile(bgFile));
                    }else {
                        startCrop(data.getData());
                    }
                    /*if (data != null) {
                        String imagePath;
                        Uri uri = data.getData();
                        if (uri != null) {
                            *//*if (!TextUtils.isEmpty(uri.getAuthority())) {
                                Cursor cursor = getContentResolver().query(uri,
                                        new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                                if (null != cursor) {
                                    cursor.moveToFirst();
                                    imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                                    cursor.close();
                                }else {
                                    imagePath = uri.getPath();
                                }
                            } else {
                                imagePath = uri.getPath();
                            }*//*
                           // Log.i(TAG, "onActivityResult: --------"+imagePath);
                            cropPic(uri);
                        } else {
                            Toast.makeText(this, "图片没找到", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }*/
                    break;
                case ConstantSet.SELECTPICTURE:
                    if(data == null){
                        startCrop(Uri.fromFile(bgFile));
                    }else {
                        startCrop(data.getData());
                    }
                    /*if (data != null) {
                        String imagePath;
                        Uri uri = data.getData();
                        if (uri != null) {
                           *//* if (!TextUtils.isEmpty(uri.getAuthority())) {
                                Cursor cursor = getContentResolver().query(uri,
                                        new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                                if (null != cursor) {
                                    cursor.moveToFirst();
                                    imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                                    cursor.close();
                                }else {
                                    imagePath = uri.getPath();
                                }
                            } else {
                                imagePath = uri.getPath();
                            }*//*
                            cropPic(uri);
                        } else {
                            Toast.makeText(this, "图片没找到", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }*/
                    break;
                case ConstantSet.CROPPICTURE:
                    Bitmap cropBitmap = BitmapFactory.decodeFile(ConstantSet.bgFile.getPath());
                   /* relaAddFront.setVisibility(View.GONE);
                    circleFront.setVisibility(View.VISIBLE);
                    circleFront.setImageBitmap(cropBitmap);*/
                    if (flag == 0) {//正面
                        relaAddFront.setVisibility(View.GONE);
                        circleFront.setVisibility(View.VISIBLE);
                        circleFront.setImageBitmap(cropBitmap);
                        //上传图片
                        setOssImage(ConstantSet.bgFile.getPath(), "front");//上传图片
                    } else if (flag == 1) {//反面
                        relaAdd.setVisibility(View.GONE);
                        circleReverse.setVisibility(View.VISIBLE);
                        circleReverse.setImageBitmap(cropBitmap);
                        setOssImage(ConstantSet.bgFile.getPath(), "other");//上传图片
                    }
                   /* Uri uri = data.getData();
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = data.getParcelableExtra("data");
                    relaAddFront.setVisibility(View.GONE);
                    circleFront.setVisibility(View.VISIBLE);
                    circleFront.setImageBitmap(bitmap);
                    Log.i(TAG, "onActivityResult: ------"+data.getData());
                    //Uri uri = data.getData();
                    if (uri != null) {
                        String imagePath;
                        if (!TextUtils.isEmpty(uri.getAuthority())) {
                            Cursor cursor = getContentResolver().query(uri,
                                    new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                            if (null != cursor) {
                                cursor.moveToFirst();
                                imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                                cursor.close();
                            }else {
                                imagePath = uri.getPath();
                            }
                        } else {
                            imagePath = uri.getPath();
                        }
                        Bitmap bitmap1 = BitmapFactory.decodeFile(imagePath);
                        if (flag == 0) {//正面
                            relaAddFront.setVisibility(View.GONE);
                            circleFront.setVisibility(View.VISIBLE);
                            circleFront.setImageBitmap(bitmap1);
                            //上传图片
                            setOssImage(imagePath,"front");//上传图片
                        } else if (flag == 1) {//反面
                            relaAdd.setVisibility(View.GONE);
                            circleReverse.setVisibility(View.VISIBLE);
                            circleReverse.setImageBitmap(bitmap1);
                            setOssImage(imagePath,"other");//上传图片
                        }
                    } else {
                        Toast.makeText(this, "图片没找到", Toast.LENGTH_SHORT).show();
                    }*/
                    break;
            }
        }
    }

    /**
     * @return
     * @method
     * @description 上传图片到oss服务器
     * @date: 2018/9/25 15:54
     * @author: ljp
     */
    private void setOssImage(String image, String side) {
        String name = side + Utils.getMobile(mobile) + System.currentTimeMillis();//图片名称
        new Thread(new Runnable() {
            @Override
            public void run() {
                OssClient.getInstance().init(context).
                        upload(name, image, OssConfig.HEAD, new OssClient.OnUploadFile() {
                            @Override
                            public void onUploadFileSuccess(String info) {
                                images.add(info);
                                Log.i(TAG, "onUploadFileSuccess: --image---" + info);
                            }

                            @Override
                            public void onUploadFileFailed(String errCode) {

                            }
                        });
            }
        }).start();
    }

    /**
     * 跳转裁剪
     *
     * @param data
     */
    private void startCrop(Uri data) {
        CropBean albumCropBean = new CropBean();
        albumCropBean.dataUri = data;
        albumCropBean.outputX = DisplayUtil.dp2px(activity, Utils.getSrecchWidth(context));
        albumCropBean.outputY = DisplayUtil.dp2px(activity, 800);
        Log.i(TAG, "startCrop: -------" + DisplayUtil.dp2px(activity, 130));
        albumCropBean.caculateAspect();
        albumCropBean.isReturnData = false;
        albumCropBean.saveUri = Uri.fromFile(ConstantSet.bgFile);
        //跳转裁剪
        Utils.startCrop(this, albumCropBean, ConstantSet.CROPPICTURE);
    }

    /**
     * 跳转到系统裁剪图片页面
     *
     * @param imagePath 需要裁剪的图片路径
     */
    private void cropPic(Uri imagePath) {
       /* File file = new File(imagePath);
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //Uri contentUri = FileProvider.getUriForFile(this, "com.voicechat.firstmet.fileprovider", file);
            Uri contentUri = FileProvider.getUriForFile(context,
                    context.getPackageName() + ".android7.fileprovider",
                    file);
            intent.setDataAndType(contentUri, "image/*");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "image/*");
        }
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 0);
        intent.putExtra("aspectY", 0);
       // intent.putExtra("outputX", 150);
       // intent.putExtra("outputY", 150);
       // intent.putExtra("return-data", true);
        intent.putExtra("scale", true);
        startActivityForResult(intent, ConstantSet.CROPPICTURE);*/
// 调用系统中自带的图片剪裁
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(imagePath, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        //intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        intent.putExtra("scale", true);
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + ".jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, ConstantSet.CROPPICTURE);

        /*Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imagePath, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 0);
        intent.putExtra("aspectY", 0);
        // outputX outputY 是裁剪图片宽高
      //  intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 130);
       // intent.putExtra("return-data", true);
        intent.putExtra("scale", true);
        startActivityForResult(intent, ConstantSet.CROPPICTURE);*/
    }


    @OnClick(R.id.tv_back_home)
    public void onClick() {
        finish();
    }
}
